﻿using Company.Logger;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Hardware.Camera
{
    /// <summary>
    /// 相机抽象基类（只实现大体操作流程，具体实现由子类去完成）
    /// </summary>
    public abstract class CameraBase : ICamera
    {
        public bool Initialized { get; private set; }

        public event Action<object> OnTrigger;

        public CameraConfig Config { get; private set; }

        public bool Initialize(ICameraConfigProvider provider)
        {
            Config = provider.CameraConfig;
            provider.OnChanged += () =>
            {
                Logs.LogInfo($"相机重新初始化 Width：{provider.CameraConfig.Width}，Height：{provider.CameraConfig.Height}");
                DoInitialize();
            };

            if (Initialized)
            {
                Logs.LogError(new InvalidOperationException("相机重复初始化！"));
            }

            if (DoInitialize())
            {
                Initialized = true;
                return true;
            }

            return false;
        }

        public bool Trigger()
        {
            if (!Initialized)
            {
                throw new InvalidOperationException("请先初始化相机！");
            }

            if (DoTrigger())
            {
                return true;
            }

            return false;
        }

        public bool Close()
        {
            if (Initialized)
            {
                if (DoClose())
                {
                    Initialized = false;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 具体子类来控制回调，回调给外部真正的使用者
        /// </summary>
        protected void TriggerCallback(object cameraImage)
        {
            OnTrigger?.Invoke(cameraImage);
        }

        // 具体实现由子类去完成
        public abstract bool DoInitialize();
        public abstract bool DoTrigger();
        public abstract bool DoClose();
    }
}
